// Copyright 2022-2024 use-ink/contracts-ui authors & contributors
// SPDX-License-Identifier: GPL-3.0-only

import { useMemo, useState } from 'react';
import { GroupBase } from 'react-select';
import { Dropdown } from '../common/Dropdown';
import { Account } from './Account';
import { Buttons, Button } from '../common/Button';
import { createAccountOptions } from 'ui/util/dropdown';
import type { DropdownOption, DropdownProps, ValidFormField } from 'types';
import { useApi, useDatabase } from 'ui/contexts';
import { classes } from 'lib/util';
import { useDbQuery } from 'ui/hooks';

import { web3Accounts, web3Enable, web3AccountsSubscribe, web3FromAddress } from '@polkadot/extension-dapp';
import { useNavigate } from 'react-router-dom';
type Props = ValidFormField<string> & Omit<DropdownProps<string>, 'options'>;

export function Option({ label, value }: DropdownOption<string>) {
  return <Account className="p-1.5" name={label} value={value} />;
}

function Select({
  isDisabled,
  onChange,
  options,
  placeholder = 'Select account',
  className,
  value,
  onCreate,
}: DropdownProps<string>) {
  return (
    <Dropdown
      className={classes('account-select', className)}
      formatOptionLabel={Option}
      isDisabled={isDisabled}
      isSearchable
      onChange={onChange}
      onCreate={onCreate}
      options={options}
      placeholder={placeholder}
      value={value}
    />
  );
}

export function AccountSelect({ placeholder = 'Select account', ...props }: Props) {
  const { accounts, setAccounts} = useApi();
  console.log('accounts', accounts)
  const navigate = useNavigate()
  // let accounts = [];


  async function Login() {
    console.log('login')
  }

  async function LoginOut() {
    // 启用扩展程序
    const extensions = await web3Enable('contracts-ui');

    if (extensions.length === 0) {
      console.error('No Polkadot extension found.');
      return;
    }

    // 获取当前账户
    const accounts = await web3Accounts();
    if (accounts.length === 0) {
      console.error('No accounts found.');
      return;
    }
    // 选择第一个账户（可以根据需求选择其他账户）
    const account = accounts[0];
    // 从扩展程序获取 provider
    const { signRaw } = await web3FromAddress(account.address);
    setAccounts([])
    // setPreferredEndpoint('ws://')
    // setEndpoint('ws://')
    // 断开连接的操作示例
    // 请注意 Polkadot.js 并没有提供直接的 API 进行取消连接
    // 一般情况下，我们可以通过管理账户或重新加载页面来达到相同的效果
    navigate('/')
    // console.log(`Disconnected from account ${account.address}`);
    // 在实际应用中，你可能需要实现具体的取消连接逻辑
  }
  return (
    // <Select options={createAccountOptions(accounts || [])} placeholder={placeholder} {...props} />
    <ul>
      {
        accounts && accounts.map((account) => (
          <li className='flex justify-between items-center pt-3 pb-3 mb-5 rounded-lg bg-gray-100 p-2 px-4 dark:bg-gray-800 dark:text-white system:bg-blue-800 system:text-white'>
            <span className='text-sm '>
              {account.meta.name}
            </span>
            <AccountStatus isline={account.meta.isInjected}></AccountStatus>
          </li>
        ))
      }
    </ul>
  );
}

export function AccountStatus({isline = false}) {
   return (
      <div className='w-16 flex flex-row justify-start items-center'>
        {
          isline && <div className='w-1 h-1 rounded-full  bg-green-300 dark:bg-blue-700'> </div>
        }
        <span className='ml-3'>line</span>
      </div>
   )
}


export function AddressSelect({ placeholder = 'Select account', onChange, ...props }: Props) {
  const { accounts } = useApi();
  const { db } = useDatabase();
  const [contracts] = useDbQuery(() => db.contracts.toArray(), [db]);
  const [recent, setRecent] = useState<DropdownOption<string>[]>([]);

  const options = useMemo((): GroupBase<DropdownOption<string>>[] => {
    return [
      {
        label: 'Recent',
        options: recent,
      },
      {
        label: 'My Accounts',
        options: createAccountOptions(accounts || []),
      },
      {
        label: 'Uploaded Contracts',
        options: (contracts || []).map(({ name, address }) => ({
          label: name,
          value: address,
        })),
      },
    ];
  }, [accounts, contracts, recent]);

  const handleCreate = (inputValue: string) => {
    setRecent([...recent, { label: inputValue, value: inputValue }]);
    onChange(inputValue);
  };

  return (
    <Select
      onChange={onChange}
      options={options}
      placeholder={placeholder}
      {...props}
      onCreate={handleCreate}
    />
  );
}
